/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import { IncrementalTask } from '../external/task/incremental-task.js';
import { FsOptions } from '../internal/snapshot/util/file-set.js';
import { HvigorLogger } from '../log/hvigor-log.js';

import { IncrementalDecoratorType } from './types.js';

const _toString = Object.prototype.toString;
const _hasOwn = Object.prototype.hasOwnProperty;
const DECLARATOR_CONTAINER = Symbol('DECLARATOR_CONTAINER');

export const incrementalDeclaratorLogger = HvigorLogger.getLogger('incremental-declarator');

interface DecoratorContainerMember {
  propertyKey: string;
  declaratorType: IncrementalDecoratorType;
  options?: FsOptions;
}

/**
 * 在target对象上，设置一个不可枚举的属性。
 * 其中。key为Symbol，可以保证全局唯一，不会存在属性名冲突
 * 值为数组，用于储存装饰器装饰的属性名。装饰器类型，以及后续所需的额外参数（FsOption）
 * @param target
 */
export const setSelfDeclaratorContainer = (target: IncrementalTask): void => {
  if (!_hasOwn.call(target, DECLARATOR_CONTAINER)) {
    Object.defineProperty(target, DECLARATOR_CONTAINER, {
      value: [],
      configurable: false,
      enumerable: false,
    });
  }
};

/**
 * 获取自身的基于装饰器装饰的属性
 * @param target
 */
export const getSelfDeclaratorContainer = (target: IncrementalTask): undefined | DecoratorContainerMember[] => {
  if (!_hasOwn.call(target, DECLARATOR_CONTAINER)) {
    return;
  }

  return (target as any)[DECLARATOR_CONTAINER] as DecoratorContainerMember[];
};

/**
 * 判断当前任务是否存在增量装饰器装饰的属性
 * @param target
 */
export const hasIncrementalDecorator = (target: IncrementalTask): boolean => {
  return !!(target as any)[DECLARATOR_CONTAINER]?.length;
};

/**
 * _toString.call(’xxx‘)会返回 [object String]之类的，用此方式可以精准获取入参的类型
 * @param param
 */
export const getType = (param: any): string => {
  const start = '[object '.length;
  return _toString.call(param).slice(start, -1);
};
